var express = require('express');
var router = express.Router();
var path  =require('path');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/douban";

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/login', function(req, res) {
    console.log(req.query.username,req.query.password,req.param('username'));
    res.send('get login success');
});

router.post('/loginAction',function(req,res,next){
    var username = req.body.username;
    var password = req.body.password;

    var findData = function(db,callback){
      var conn = db.collection('user');
      var data = {username:username,password:password};
      conn.find(data).toArray(function(err,results){
        if(err){
          console.log(err);
          return;
        }
        callback(results);
      });
    }

    MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        console.log(err);
        return;
      }else{
        findData(db,function(results){
          if(results.length>0){
            req.session.username = results[0].username;
            res.redirect('/');
          }else{
            req.session.error = '用户名或密码错误';
            res.redirect('/login');
          }
          db.close();
        });
      }
    });
});

router.post('/registerAction',function(req,res,next){
    var username = req.body.username;
    var password = req.body.password;

    MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        return;
      }else{
        var conn = db.collection('user');
        var data = {username:username,password:password};
        var dataname = {username:username};
        conn.find(dataname).toArray(function(err,results){
          if(results.length>0){
            req.session.repeat = '该用户名已被注册';
           res.redirect('/register');
          }else{
            conn.insert(data,function(err,results){
              res.redirect('/login');
              db.close();
            })
          }
        })

      }
    })
});

module.exports = router;
